package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongdb.MovementsApi;
import com.tanhua.api.mongdb.RecommentApi;
import com.tanhua.domain.UserHolder;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mogo.Visitors;
import com.tanhua.domain.vo.VisitorsVo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MovementsService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private MovementsApi movementsApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private RecommentApi recommentApi;

    public ResponseEntity findHistory() {

        // 1 从redis中获取上次登录时间
        Long userId = UserHolder.findUser().getId();
        String time = stringRedisTemplate.opsForValue().get("visitors_user_" + userId);
        List<VisitorsVo> visitorsVoList=new ArrayList<>();
        if(time!=null){
            // 2 查到了--拿数据 visitors
            List<Visitors> list= movementsApi.findVisitors(userId,Long.parseLong(time));
            if(CollectionUtil.isNotEmpty(list)){
                for (Visitors visitors : list) {
                    //3 查询userInfo数据
                    UserInfo userInfo = userInfoApi.findByUser(visitors.getVisitorUserId());
                    //4 封装app需要的vo
                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setUserInfo(userInfo);
                    // 5 查询缘分值
                    Long score = recommentApi.findScore(userId, visitors.getVisitorUserId());
                    visitorsVo.setFateValue(score);
                    visitorsVoList.add(visitorsVo);
                }
            }
        }

        //5 将当前时间放入redis中进行覆盖
        stringRedisTemplate.opsForValue().set("visitors_user_" + userId,System.currentTimeMillis()+"");

        return ResponseEntity.ok(visitorsVoList);

    }
}
